// Created by Roman Novitsky on 29.04.2009


#region Imported Namespaces


using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;


#endregion


namespace WtfManager.UIManager
{
  [ValueConversion(typeof(IList), typeof(CollectionViewSource), ParameterType = typeof(CollectionViewSettings))]
  public class ItemsSourceToCollectionViewSourceConverter: IValueConverter
  {
    #region Fields


    private static ItemsSourceToCollectionViewSourceConverter _instance;


    #endregion


    #region Constructors/Finalizers


    private ItemsSourceToCollectionViewSourceConverter()
    {
    }


    #endregion


    #region Properties/Indexers


    public static ItemsSourceToCollectionViewSourceConverter Instance
    {
      get
      {
        if (_instance == null)
        {
          _instance = new ItemsSourceToCollectionViewSourceConverter();
        }

        return _instance;
      }
    }


    #endregion


    #region Methods


    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      var list = value as IList;

      if (list == null)
      {
        return value;
      }

      var viewSettings = parameter as CollectionViewSettings;

      if (viewSettings == null)
      {
        return value;
      }

      var collectionViewSource = new ListCollectionView(list);

      foreach (SortDescription sortDescription in viewSettings.SortDescriptionCollection)
      {
        collectionViewSource.SortDescriptions.Add(sortDescription);
      }

      collectionViewSource.Filter += viewSettings.Filters.Predicate;

      return collectionViewSource;
    }


    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotSupportedException();
    }


    #endregion
  }
}